const { Discussion } = require('../model/discussions')
const { Reply } = require("../model/reply")
const { Topic } = require("../model/topics")
const {User} = require("../model/user")
const moment = require('moment-timezone');

//二级回复
exports.createDiscussion = async (req, res, next) => {
    try {
        const rootCommentId = req.query.rootCommentId
        let rootComment = await Reply.findById(rootCommentId).select("+childrenComments")
        const reply = await new Discussion({ 
            ...req.body,
            replier: req.userData._id,
            topicId: req.params.id,
            rootCommentId: rootCommentId,
            replyTo: rootComment.replier,
            createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
        })
        rootComment.childrenComments.push(reply._id)
        await rootComment.save()
        if (!reply) return res.status(200).json({
            code: 400,
            msg: "评论失败"
        })
        await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: +1 } })
        await reply.save()
        res.status(200).json({
            code: 200,
            msg: '评论成功',
            data: reply
        })
    } catch (err) {
        next(err)
    }
}

//回复二级评论
exports.replyDiscussion = async (req, res, next) => {
    try {
        const replyId = req.params.id
        let rootComment = await Discussion.findById(replyId)
        // console.log(rootComment)
        if (!rootComment) return res.status(200).json({
            code: 400,
            msg: "回复失败"
        })
        const comment = await new Discussion({ 
            ...req.body, 
            replier: req.userData._id, 
            topicId: rootComment.topicId, 
            rootCommentId: rootComment.rootCommentId, 
            replyTo: rootComment.replier,
            createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
        })
        //一级评论
        const realRootComment = await Reply.findById(rootComment.rootCommentId).select("+childrenComments")
        if (!realRootComment) return res.status(200).json({
            code: 400,
            msg: "回复失败"
        })

        realRootComment.childrenComments.push(comment._id)
        await realRootComment.save()
        await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: +1 } })
        await comment.save()

        await Discussion.findByIdAndUpdate(comment._id,{
            tier:"third"
        })
        res.status(200).json({
            code: 200,
            msg: '回复成功',
            data: comment
        })
    } catch(err){
        next(err)
    }
}


exports.deleteDiscussion = async (req, res, next) => {
    try {
        let delComment = await Discussion.findById(req.params.id)
        let rootComment = delComment.rootCommentId
        console.log(delComment._id)
        let result = await Reply.findByIdAndUpdate(rootComment, { 
            $pull: { 
                childrenComments: delComment._id
            } ,
        }).select("+childrenComments")

        if(!result) return res.status(200).json({
            code:400,
            msg:"删除失败"
        })

        const data = await Discussion.findByIdAndDelete(req.params.id)

        if (!data) return res.status(200).json({
            code: 400,
            msg: '删除评论失败',
        })
        await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: -1 } })
        res.status(200).json({
            code: 200,
            msg: '删除评论成功',
            data: data
        })
    } catch (err) {
        next(err)
    }
}
//点赞评论
exports.likeDiscussion = async (req, res, next) => {
    try {
        let userId = req.userData._id
        const followId = req.params.id
        const user = await User.findById(userId.toString()).select("+likingReplies")
        //如果没有点赞则点赞
        if (!user.likingReplies.map(id => id.toString()).includes(followId)) {
            user.likingReplies.push(followId)
            await user.save()
            const changeComments=await Discussion.findByIdAndUpdate(req.params.id, { $inc: { voteCount: +1 } })
            await User.findByIdAndUpdate(changeComments.replier, { $inc: { praiseCount: +1 } })
            res.status(200).json({
                code: 200,
                msg: "点赞成功",
                data: {
                    id: req.params.id
                }
            })
        } else {
            res.status(200).json({
                code: 400,
                msg: "点赞失败",
                data: {
                    id: req.params.id
                }
            })
        }
    } catch (err) {
        next(err)
    }
}

//取消点赞评论
exports.unLikeDiscussion = async (req, res, next) => {
    try {
        let userId = req.userData._id
        const user = await User.findById(userId.toString()).select("+likingReplies")
        const index = user.likingReplies.map(id => id.toString()).indexOf(req.params.id)
        if (index > -1) {
            user.likingReplies.splice(index, 1)
            await user.save()
            const changeComments=await Discussion.findByIdAndUpdate(req.params.id, { $inc: { voteCount: -1 } })
            await User.findByIdAndUpdate(changeComments.replier, { $inc: { praiseCount: -1 } })
            res.status(200).json({
                code: 200,
                msg: "操作成功",
                data: {
                    id: req.params.id
                }
            })
        } else {
            res.status(200).json({
                code: 400,
                msg: "操作失败",
                data: {
                    id: req.params.id
                }
            })
        }
    } catch (err) {
        next(err)
    }
}

